# camera_stream/views.py

from django.http import StreamingHttpResponse
from django.shortcuts import render
from django.views.decorators import gzip
import cv2
import threading

# 使用OpenCV从摄像头获取视频流
class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)  # 0表示使用默认摄像头
        self.is_streaming = False

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

# 使用generator函数生成视频流
def video_stream(camera):
    while camera.is_streaming:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

# 使用gzip压缩提高视频流的传输效率
@gzip.gzip_page
def live_video_feed(request):
    camera = VideoCamera()  # 实例化VideoCamera对象
    return StreamingHttpResponse(video_stream(camera), content_type="multipart/x-mixed-replace;boundary=frame")

def start_stream(request):
    camera = VideoCamera()  # 实例化VideoCamera对象
    camera.is_streaming = True
    return render(request, 'index.html')

def stop_stream(request):
    camera = VideoCamera()  # 实例化VideoCamera对象
    camera.is_streaming = False
    return render(request, 'index.html')

def index(request):
    return render(request, 'index.html')


def chat(request):
    return render('text.html')
